package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 今日佳人服务实现
 */
@Service
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 今日佳人
     * @param toUserId
     * @return
     */
    @Override
    public RecommendUser todayBest(Long toUserId) {
        //仅仅推荐今日佳人
        String currentDate = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
        //1.根据当前登录用户id 查询缘分值最高一位用户
        Query query = new Query();
        //query.addCriteria(Criteria.where("toUserId").is(toUserId).and("date").is(currentDate));
        query.addCriteria(Criteria.where("toUserId").is(toUserId));
        query.with(Sort.by(Sort.Order.desc("score")));
        return mongoTemplate.findOne(query, RecommendUser.class);
    }

    /**
     * 首页推荐用户分页查询
     * @param toUserId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult<RecommendUser> findPage(Long toUserId, Integer page, Integer pagesize) {
        //当前用户id作为查询条件
        Query query = new Query();
        query.addCriteria(Criteria.where("toUserId").is(toUserId));
        //1.查询总记录数
        long counts = mongoTemplate.count(query, RecommendUser.class);
        //2.根据条件分页查询当前页面数据
        //方式一：
        //query.limit(pagesize).skip((page-1)*pagesize);

        //方式二：
        //PageRequest pageable = PageRequest.of(page,pagesize,Sort.by(Sort.Order.desc("score")));
        PageRequest pageable = PageRequest.of(page,pagesize,Sort.by(Sort.Order.asc("id")));
        query.with(pageable);
        List<RecommendUser> recommendUserList = mongoTemplate.find(query, RecommendUser.class);
        //3.封装PageResult<RecommendUser>
        long pages = counts/pagesize + counts%pagesize > 0 ? 1:0;
        return new PageResult<RecommendUser>(counts,(long)pagesize,pages,(long)page,recommendUserList);
    }

    /**
     * 根据佳人用户id 和 当前登录用户id 从推荐表 中 查询缘分值
     */
    @Override
    public Long queryForScore(Long beautyUserId, Long userId) {
        Query query = new Query(Criteria.where("userId").is(beautyUserId).and("toUserId").is(userId));
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        if(recommendUser == null || recommendUser.getScore() == null){
            return 60l;
        }
        return recommendUser.getScore().longValue();
    }

}
